package com.emm.yixun.customer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jws.WebService;

import com.emm.yixun.common.model.dto.*;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.HaveReceiveRefundService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.MortgageRecordFollowService;
import com.emm.yixun.basic.service.MortgageRecordService;
import com.emm.yixun.basic.service.NeedReceiveRefundService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.SubscribeTransService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.Image;
import com.emm.yixun.common.model.MortgageRecord;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.SignedInfo;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.SubscribeTrans;
import com.emm.yixun.common.model.TransactionRelation;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.BusinessFlagEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.model.enums.HousingFundTypeEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.ReceivablesTypeEnum;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;
import com.emm.yixun.customer.service.impl.app.manage.CusAppNoticeManage;

@Service("signedServiceFacade")
@WebService(name = "com.emm.yixun.customer.service.SignedServiceFacade")
public class SignedServiceFacadeImpl implements SignedServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private SignedService service;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private MortgageRecordService mortgageRecordService;
	@Autowired
	private MortgageRecordFollowService mortgageRecordFollowService;
	@Autowired
	private SignedService signedService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private UserService userService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private PayDepositTransactionalService payDepositTransactionalService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;

	@Autowired
	private PayDepositService payDepositService;

	@Autowired
	private ImageService imageService;
	@Autowired
	private SubscribeTransService subscribeTransService;

	@Override
	public Response<SignedDto> save(SignedDto dto) {
		Response<SignedDto> response = new Response<SignedDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			SignedDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(SignedDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			SignedDto mDto = new SignedDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<SignedInfo> findByIdInfo(Long id) {
		Response<SignedInfo> response = new Response<SignedInfo>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Signed entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				SignedInfo info = new SignedInfo();
				BeanUtils.copyProperties(entity, info);
				String str = gerUserName(entity.getId(), entity.getMerchantId(), entity.getDealCategory());
				if(!str.equals("")){
					info.setUserName(str);
				}else{
					UserDto userDto = new UserDto();
					userDto.setUserCode(entity.getUserCode());
					User user = userService.selectByDto(userDto);
					info.setUserName(user.getUserName());
				}

				// 查询附件
				ImageDto imageDto = new ImageDto();
				imageDto.setMerchantId(entity.getMerchantId());
				imageDto.setObjectId(id);
				imageDto.setImgType(ImgTypeEnum.SIGNED.getNo());
				List<Image> list = imageService.selectListByDto(imageDto);
				String signedFileUrl = "";
				if (null != list) {
					for (Image image : list) {
						if (!signedFileUrl.equals("")) {
							signedFileUrl = signedFileUrl + "|";
						}
						String smallUrl = image.getSmallUrl();
						signedFileUrl = signedFileUrl + smallUrl;
					}
				}
				info.setSignedFileUrl(signedFileUrl);

				response.success(info);
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	public String gerUserName(Long signerId, Long merchantId, String type) {
		TransactionRelationDto tranDto = new TransactionRelationDto();
		tranDto.setBusinessId(signerId);
		tranDto.setMerchantId(merchantId);
		tranDto.setRelationType("6");
		tranDto.setDelFlag("0");
		List<TransactionRelation> list = transactionRelationService.selectListByDto(tranDto);
		if (list != null) {
			String str = "";
			for (int i = 0; i < list.size(); i++) {
				TransactionRelation tran = (TransactionRelation) list.get(i);
				User user = userService.selectById(tran.getRelationAgentid());
				if (user != null) {
					str += user.getUserName();
					if ("3".equals(type)) {
						str += "(" + tran.getProportionCommission() + "%)，";
					}
				}
			}
			return str;
		}
		return null;
	}

	@Override
	public Response<Signed> findById(Long id) {
		Response<Signed> response = new Response<Signed>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			Signed entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<Signed> findByDto(SignedDto dto) {
		ResponseList<Signed> response = new ResponseList<Signed>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<Signed> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<Signed> findPageByDto(SignedDto dto, Integer begin, Integer row) {
		Page<Signed> response = new Page<Signed>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<Signed> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.customer.service.SignedServiceFacade#getSignedDtoList(com.emm.
	 * yixun.common.model.dto.SignedDto, java.lang.Integer, java.lang.Integer)
	 */

	public SignedDto setSignedQuery(SignedDto reqDto) {
		// 数据权限
		if (SysConstants.openDataPermission) {
			String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(),
					reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
			String[] dataPermissionArr = dataPermission.split(":");
			if ("00".equals(dataPermissionArr[0])) {
				return null;
			}
			reqDto.setDataPermission(dataPermissionArr[1]);
		}
		return reqDto;
	}

	@Override
	public Response<Page<SignedDto>> getSignedDtoList(SignedDto reqDto, Integer pageSize, Integer pageNum) {
		Response<Page<SignedDto>> resDto = new Response<Page<SignedDto>>();
		try {
			reqDto = setSignedQuery(reqDto);
			if (reqDto == null) {
				resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
				resDto.setSuccess(false);
				return resDto;
			}
			Page<SignedDto> page = service.getPageDtoModel(reqDto, PageUtil.begin(pageNum, pageSize), pageSize);
			page.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(page);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	@Override
	public Response<SignedDto> addSigned(String params, User user) throws Exception{
		/**
		 * 签约 1.保存签约信息 2.保存家庭成员信息 3.保存折扣审批信息
		 */
		Response<SignedDto> response = new Response<SignedDto>();
		if (StringUtils.isBlank(params)) {
			response.fail("80000", "参数不能为空！");
			return response;
		}
		SignedDto signedDto = JSONObject.parseObject(params, SignedDto.class);
		if (StringUtils.isNotBlank(signedDto.getSignCode()) && null == signedDto.getId()) {
			SignedDto dto = new SignedDto();
			dto.setSignCode(signedDto.getSignCode());
			dto.setProjectId(signedDto.getProjectId());
			List<Signed> signed = service.selectListByDto(dto);
			if (signed != null && signed.size() != 0) {
				for (Signed s : signed) {
					String businessStatus = s.getBusinessStatus();
					String auditStatus = s.getAuditStatus();
					// 合同编号相同 && 非已退回状态 && 业务状态为签约或者更名 则认为是合同号码重复
					if (!auditStatus.equals(AuditStatusEnum.REJECT.getNo())) {
						if (businessStatus.equals("1") || businessStatus.equals("4")) {
							logger.error("签约错误", "合同编号重复");
							response.fail("80000", "合同编号重复！");
							return response;
						}
					}
				}

			}
		}
		// 验证是否重复提交
		SignedDto dtoQuery = new SignedDto();
		dtoQuery.setRoomId(signedDto.getRoomId());
		dtoQuery.setCustomerId(signedDto.getCustomerId());
		List<Signed> signedObjList = service.selectListByDto(dtoQuery);
		if (signedObjList != null) {
			for (Signed s : signedObjList) {
				String businessStatus = s.getBusinessStatus();
				String businessSecStatus = s.getBusinessSecStatus();
				SubscribeTransDto trans = new SubscribeTransDto();
				trans.setSigId(s.getId());
				trans.setDelFlag(DelFlagEnum.UNDEL.getNo());
				List<SubscribeTrans> tranList = subscribeTransService.selectListByDto(trans);
				if (tranList != null && tranList.size() > 0) {
					continue;
				}
				String auditStatus = s.getAuditStatus();
				// 非已退回或待提交状态
				if (!auditStatus.equals(AuditStatusEnum.REJECT.getNo())
						&& !auditStatus.equals(AuditStatusEnum.TOSUBMIT.getNo())) {
					// 业务状态为签约或者更名，则认为是重复提交
					if (businessStatus.equals("1") || businessStatus.equals("4")) {
						if (StringUtils.isEmpty(businessSecStatus)
								|| (businessSecStatus.equals("1") || businessSecStatus.equals("4"))) {
							response.setSuccess(false);
							response.setResultMessage("请勿重复提交!");
							return response;
						}
					}
				}

			}

		}

		if (signedDto.getSubscribeId() != null) {
			Subscribe subcribe = subscribeService.selectById(signedDto.getSubscribeId());
			// 认购ID 不为空， 查找是否有认筹ID
			signedDto.setPayDepositId(subcribe.getPayDepositId());
			signedDto.setPayDepositCode(subcribe.getPayDepositCode());
		}
		signedDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
		signedDto.setBusinessStatus("1");
		ProjectRoom projectRoom = projectRoomService.selectById(signedDto.getRoomId());
		if (null != projectRoom) {
			signedDto.setAccessCode(projectRoom.getProjectCode());
			signedDto.setProjectId(projectRoom.getProjectId());
			signedDto.setProjectCode(projectRoom.getProjectCode());
		}
		// 非认购转签约需要判断房源状态
		if (signedDto.getSubscribeId() == null) {
			String roomStatus = projectRoom.getRoomStatus();
			if (RoomStatusEnum.BUY.getNo().equals(roomStatus)) {
				response.fail("80000", "该房源已被认购！");
				return response;
			} else if (RoomStatusEnum.SIGN.getNo().equals(roomStatus)) {
				response.fail("80000", "该房源已被签约！");
				return response;
			} else if (RoomStatusEnum.RETAIN.getNo().equals(roomStatus)) {
				response.fail("80000", "该房源已被保留！");
				return response;
			} else if (RoomStatusEnum.MA.getNo().equals(roomStatus)) {
				response.fail("80000", "该房源已被销控！");
				return response;
			} else if (RoomStatusEnum.SALEL.getNo().equals(roomStatus)) {
				response.fail("80000", "该房源暂不可售");
				return response;
			}
		}

		// 处理支付信息
		String extraInformation = signedDto.getExtraInformation();
		if (StringUtils.isNotBlank(extraInformation)) {
			JSONObject object = JSON.parseObject(extraInformation);
			JSONArray paymentDetails = object.getJSONArray("paymentDetails");
			JSONObject result = new JSONObject();
			result.put("depositAmount", object.get("depositAmount"));
			result.put("subscribeAmount", object.get("subscribeAmount"));
			JSONArray array = new JSONArray();
			for (int i = 0; i < paymentDetails.size(); i++) {
				String rowStr = paymentDetails.getString(i);
				JSONObject row = JSON.parseObject(rowStr);
				String receivablesDate = row.getString("receivablesDate");
				if (receivablesDate.indexOf("T") != -1)
					receivablesDate = receivablesDate.replaceFirst("T", " ");
				row.put("receivablesDate", receivablesDate);
				array.add(row);
			}
			result.put("paymentDetails", array);
			signedDto.setExtraInformation(result.toJSONString());
		}

		signedDto.setMerchantId(user.getMerchantId());
		signedDto.setCreateUserId(user.getId());


		Customer customer = customerService.selectById(signedDto.getCustomerId());
		signedDto.setUserCode(customer.getUserCode());
		signedDto.setDelFlag("0");
		signedDto.setUpdateUserId(user.getId());
		signedDto.setUpdateTime(new Date());
		SignedDto successSignedDto = payDepositTransactionalService.addSignedWithTransactional(params, user,
				signedDto);
		response.success(successSignedDto);
		return response;
	}

	public void conversionHaveReceive(Signed signed, List<NeedReceiveRefund> needList) {
		List<HaveReceiveRefund> convertList = new ArrayList<HaveReceiveRefund>();
		// 查询认筹已收
		// 查询认购已收
		// 绑定签约应收第一条
		if (signed.getSubscribeId() != null) {
			Subscribe subscribe = subscribeService.selectById(signed.getSubscribeId());
			// 认购转签约
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(subscribe.getId());
			// 已收
			haveReceiveRefundDto.setDocType("0");
			// 认购
			haveReceiveRefundDto.setReceivablesType("1");
			// 正常
			haveReceiveRefundDto.setTransferStatus("0");
			List<HaveReceiveRefund> haveReceiveList = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
			if (null != haveReceiveList && haveReceiveList.size() > 0) {
				convertList.addAll(haveReceiveList);
			}

			// //判断是否认筹转认购
			// if(null!=subscribe.getPayDepositId()){
			// HaveReceiveRefundDto dto1=new HaveReceiveRefundDto();
			// dto1.setRelationId(subscribe.getPayDepositId());
			// //已收
			// dto1.setDocType("0");
			// //认筹
			// dto1.setReceivablesType("0");
			// ResponseList<HaveReceiveRefund>
			// list1=haveReceiveRefundServiceFacade.findByDto(haveReceiveRefundDto);
			// if(list1.isSuccess() && null!=list1.getEntity() &&
			// list1.getEntity().size()>0){
			// convertList.addAll(list1.getEntity());
			// }
			// }

		} else if (signed.getPayDepositId() != null) {
			// 认筹转认购
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(signed.getPayDepositId());
			// 已收
			haveReceiveRefundDto.setDocType("0");
			// 认筹
			haveReceiveRefundDto.setReceivablesType("0");
			List<HaveReceiveRefund> haveReceiveList = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
			if (null != haveReceiveList && haveReceiveList.size() > 0) {
				convertList.addAll(haveReceiveList);
			}
		}

		// 查找应收
		NeedReceiveRefund tempNeedReceive = null;
		for (NeedReceiveRefund nrr : needList) {
			String housingFundTyp = nrr.getHousingFundType();
			if (housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_5.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_12.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo())) {
				tempNeedReceive = nrr;
				break;
			}
		}
		if (null != tempNeedReceive) {
			for (HaveReceiveRefund hrr : convertList) {
				try {
					// 原记录更新为转出
					HaveReceiveRefundDto updateDto = new HaveReceiveRefundDto();
					updateDto.setId(hrr.getId());
					updateDto.setTransferStatus("1");
					haveReceiveRefundService.update(updateDto);
					// 转到应收下
					HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
					haveReceiveRefundDto = BeanUtil.convert2T(haveReceiveRefundDto, hrr);
					haveReceiveRefundDto.setId(null);
					haveReceiveRefundDto.setRelationId(signed.getId());
					haveReceiveRefundDto.setReceivablesType("2");
					haveReceiveRefundDto.setReceivablesId(tempNeedReceive.getId());
					haveReceiveRefundDto.setHousingFundType(tempNeedReceive.getHousingFundType());
					haveReceiveRefundDto.setBusinessFlag(tempNeedReceive.getBusinessFlag());
					haveReceiveRefundDto.setCreateTime(new Date());
					haveReceiveRefundService.create(haveReceiveRefundDto);
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}

	}

	public void saveNeedReceive(SignedDto signed, JSONObject paramsJson) throws Exception {
		JSONArray needReceive = paramsJson.getJSONArray("needReceive");
		if (null != needReceive && needReceive.size() > 0) {
			for (int i = 0; i < needReceive.size(); i++) {
				String needReceiveStr = (String) needReceive.get(i);
				NeedReceiveRefundDto needReceiveRefundDto = JSONObject.parseObject(needReceiveStr,
						NeedReceiveRefundDto.class);
				needReceiveRefundDto.setRelationId(signed.getId());
				needReceiveRefundDto.setBusinessType("2");
				needReceiveRefundDto.setCustomerId(signed.getCustomerId());
				needReceiveRefundDto.setRoomId(signed.getRoomId());
				needReceiveRefundDto.setStatus("1");
				needReceiveRefundDto.setPostponedStatus("0");
				needReceiveRefundDto.setDocType("0");
				needReceiveRefundDto.setRemark("签约收款");
				needReceiveRefundDto.setMerchantId(signed.getMerchantId());
				needReceiveRefundDto.setPaymentMethod(signed.getPaymentMethod());
				needReceiveRefundDto.setUserCode(signed.getUserCode());
				needReceiveRefundDto.setAccessCode(signed.getAccessCode());
				needReceiveRefundDto.setCreateUserId(signed.getCreateUserId());
				needReceiveRefundDto.setDelFlag("0");
				needReceiveRefundDto.setUpdateUserId(signed.getUpdateUserId());
				needReceiveRefundDto.setUpdateTime(new Date());
				NeedReceiveRefundDto nrrdSaveResponse = needReceiveRefundService.create(needReceiveRefundDto);
				if (null == nrrdSaveResponse) {
					throw new Exception("保存签约应收信息错误");
				}
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.customer.service.SignedServiceFacade#selectSignedDtoList(com.
	 * emm.yixun.common.model.dto.SignedDto, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<Page<SignedDto>> selectSignedDtoList(SignedDto reqDto, Integer pageSize, Integer pageNum) {
		Response<Page<SignedDto>> resDto = new Response<Page<SignedDto>>();
		try {

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(),
						reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					resDto.setSuccess(false);
					return resDto;
				}
				reqDto.setDataPermission(dataPermissionArr[1]);
			}

			Page<SignedDto> page = service.selectPageDtoModel(reqDto, PageUtil.begin(pageNum, pageSize), pageSize);
			page.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(page);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.customer.service.SignedServiceFacade#selectSignedDtoList(com.
	 * emm.yixun.common.model.dto.SignedDto, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public ResponseList<SignedDto> selectAllDto(SignedDto reqDto) {
		ResponseList<SignedDto> resDto = new ResponseList<SignedDto>();
		try {

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(),
						reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					resDto.setSuccess(false);
					return resDto;
				}
				reqDto.setDataPermission(dataPermissionArr[1]);
			}

			List<SignedDto> list = service.selectAllDto(reqDto);
			resDto.setSuccess(true);
			resDto.setEntity(list);
			return resDto;
		} catch (Exception e) {
			logger.error("查询数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	@Override
	public ResponseList<SignedDto> allDto(SignedDto reqDto) {
		ResponseList<SignedDto> resDto = new ResponseList<SignedDto>();
		try {
			List<SignedDto> list = service.selectAllDto(reqDto);
			resDto.setSuccess(true);
			resDto.setEntity(list);
			return resDto;
		} catch (Exception e) {
			logger.error("查询数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	@Override
	public Response<SignedDto> selectChangeSignedByDto(SignedDto reqDto) {
		Response<SignedDto> response = new Response<SignedDto>();
		try {
			if (null == reqDto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			SignedDto mDto = service.selectChangeSignedByDto(reqDto);
			Signed signed = service.selectById(reqDto.getId());
			String str = gerUserName(signed.getId(), signed.getMerchantId(), signed.getDealCategory());
			if (null == mDto) {
				response.fail("90001", "数据不存在");
			} else {
				mDto.setAgentName(str);
				response.success(mDto);
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	/**
	 * 签约合同变更
	 */
	@Override
	public Response<SignedDto> contactChange(Signed signed, String params, User user, String paymentMethod) throws Exception{
		Response<SignedDto> response = new Response<SignedDto>();
		// 1、判断签约记录是否存在已收款情况
		HaveReceiveRefundDto hrrDto = new HaveReceiveRefundDto();
		hrrDto.setRelationId(signed.getId());
		hrrDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
		hrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
		Double amount = haveReceiveRefundService.haveReceiveAmount(hrrDto);
		if (null != amount && amount > 0) {
			response.setSuccess(false);
			response.setResultMessage("已收取部分签约款,合同不能变更!");
		} else {
			// 2、删除原签约记录中的应收款 NeedReceivedFunds
			NeedReceiveRefundDto nrrDto = new NeedReceiveRefundDto();
			nrrDto.setRelationId(signed.getId());
			nrrDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
			nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
			List<NeedReceiveRefund> nrrList = needReceiveRefundService.selectListByDto(nrrDto);
			if (null != nrrList && nrrList.size() > 0) {
				for (NeedReceiveRefund nrr : nrrList) {
					nrrDto = new NeedReceiveRefundDto();
					nrrDto.setId(nrr.getId());
					nrrDto.setUpdateUserId(user.getId());
					nrrDto.setDelFlag(DelFlagEnum.DEL.getNo());
					nrrDto.setRemark(nrr.getRemark() + "|合同变更删除原记录");
					needReceiveRefundService.update(nrrDto);
				}
			}
			// 3、删除按揭相关数据
			// 3.1、删除按揭记录
			// 3.2、删除按揭跟进记录
			MortgageRecordDto mrDto = new MortgageRecordDto();
			mrDto.setSignedId(signed.getId());
			List<MortgageRecord> mrList = mortgageRecordService.selectListByDto(mrDto);
			if (null != mrList && mrList.size() > 0) {
				for (MortgageRecord mr : mrList) {
					mrDto = new MortgageRecordDto();
					mrDto.setId(mr.getId());
					mrDto.setUpdateUserId(user.getId());
					mrDto.setDelFlag(DelFlagEnum.DEL.getNo());
					nrrDto.setRemark(mr.getRemark() + "|合同变更删除原记录");
					mortgageRecordService.update(mrDto);
					// 跟进变更记录
					MortgageRecordFollowDto mrfDto = new MortgageRecordFollowDto();
					mrfDto.setMortgageRecordId(mr.getId());
					mortgageRecordFollowService.destroy(mrfDto);
				}
			}
			// 4、插入新的待收款记录
			JSONArray needReceiveArray = JSONArray.parseArray(params);
			if (null != needReceiveArray && needReceiveArray.size() > 0) {
				for (int i = 0; i < needReceiveArray.size(); i++) {
					String needReceiveStr = (String) needReceiveArray.get(i);
					NeedReceiveRefundDto needReceiveRefundDto = JSONObject.parseObject(needReceiveStr,
							NeedReceiveRefundDto.class);

					needReceiveRefundDto.setRelationId(signed.getId());
					needReceiveRefundDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
					needReceiveRefundDto.setCustomerId(signed.getCustomerId());
					needReceiveRefundDto.setRoomId(signed.getRoomId());
					needReceiveRefundDto.setStatus("1");
					needReceiveRefundDto.setPostponedStatus("0");
					needReceiveRefundDto.setDocType(DocTypeEnum.COLLECTION.getNo());
					needReceiveRefundDto.setRemark("合同变更签约收款");
					needReceiveRefundDto.setMerchantId(signed.getMerchantId());
					needReceiveRefundDto.setPaymentMethod(paymentMethod);
					needReceiveRefundDto.setUserCode(signed.getUserCode());
					needReceiveRefundDto.setAccessCode(signed.getAccessCode());
					needReceiveRefundDto.setCreateUserId(signed.getCreateUserId());
					needReceiveRefundDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					needReceiveRefundDto.setUpdateUserId(signed.getUpdateUserId());
					needReceiveRefundDto.setUpdateTime(new Date());
					NeedReceiveRefundDto nrrdSaveResponse = needReceiveRefundService.create(needReceiveRefundDto);
					if (null == nrrdSaveResponse) {
						throw new Exception("保存签约应收信息错误");
					}
				}
			}
			// 5、插入新的签约按揭记录
			nrrDto = new NeedReceiveRefundDto();
			nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
			nrrDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
			nrrDto.setRelationId(signed.getId());
			nrrList = needReceiveRefundService.selectListByDto(nrrDto);
			if (null != nrrList && nrrList.size() > 0) {
				for (NeedReceiveRefund nff : nrrList) {
					if (nff.getPaymentMethod().equals(PaymentMethodEnum.LUMP_SUM.getNo())
							|| nff.getPaymentMethod().equals(PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo())) {
						continue;
					}
					String housingFundTyp = nff.getHousingFundType();
					if (housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo())
							|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo())
							|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo())) {
						continue;
					}
					MortgageRecordDto mortgageRecordDto = new MortgageRecordDto();
					mortgageRecordDto.setNeedId(nff.getId());
					mortgageRecordDto.setSignedId(signed.getId());
					mortgageRecordDto.setRoomId(signed.getRoomId());
					mortgageRecordDto.setCustomerId(signed.getCustomerId());
					mortgageRecordDto.setProjectId(signed.getProjectId());
					mortgageRecordDto.setBusinessFlag(nff.getBusinessFlag());
					mortgageRecordDto.setHousingFundType(nff.getHousingFundType());
					ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());
					if (null != projectRoom) {
						mortgageRecordDto.setRoomName(projectRoom.getCombinedName());
					} else {
						mortgageRecordDto.setRoomName("未知");
					}
					Customer customer = customerService.selectById(signed.getCustomerId());
					if (null != customer) {
						mortgageRecordDto.setCustomerName(customer.getCustomerName());
					} else {
						mortgageRecordDto.setCustomerName("未知");
					}

					mortgageRecordDto.setSignedDate(signed.getDidTime());
					mortgageRecordDto.setSignAmount(signed.getSignAmount());
					// 按揭金额
					mortgageRecordDto.setMortgageAmount(nff.getTotalReceivablesAmount());
					mortgageRecordDto.setMortgageReceivedStatus("0");
					mortgageRecordDto.setMortgageCheckStatus("0");
					mortgageRecordDto.setProcessStatus("0");

					mortgageRecordDto.setMerchantId(signed.getMerchantId());
					mortgageRecordDto.setAccessCode(signed.getAccessCode());
					mortgageRecordDto.setCreateUserId(signed.getCreateUserId());
					mortgageRecordDto.setUserCode(signed.getUserCode());
					mortgageRecordDto.setDelFlag("0");
					mortgageRecordDto.setUpdateUserId(signed.getUpdateUserId());
					mortgageRecordDto.setUpdateTime(new Date());
					mortgageRecordDto.setReceivablesFunds(nff.getReceivablesFunds());
					mortgageRecordService.create(mortgageRecordDto);
				}
			}
			// 6、修改签约中的收款方式
			SignedDto signedDto = new SignedDto();
			signedDto.setId(signed.getId());
			signedDto.setPaymentMethod(paymentMethod);
			signedService.update(signedDto);
			response.setSuccess(true);
			response.setResultMessage("签约合同变更成功!");
		}
		return response;
	}

	@Override
	public HashMap<String, Double> signedContractAmount(Long payDepositId, Long subId) {
		HashMap<String, Double> map = new HashMap<String, Double>();
		try {

			// 认筹转签约
			Double payDepositAmount = 0d;
			Double subscribeAmount = 0d;
			HaveReceiveRefundDto reFundDto = new HaveReceiveRefundDto();
			if (payDepositId != null) {
				reFundDto.setDocType(DocTypeEnum.COLLECTION.getNo());
				reFundDto.setRelationId(payDepositId);
				// reFundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_1.getNo());
				reFundDto.setReceivablesType(ReceivablesTypeEnum.DEPOSIT.getNo());
				payDepositAmount = queryHaveByDto(reFundDto);
				map.put("payAepositAmount", payDepositAmount);
				if (subId == null) {
					map.put("subscribeAmount", subscribeAmount);
				}
			}
			if (subId != null) {
				/*
				 * SubscribeTransDto trans = new SubscribeTransDto(); trans.setSubId(subId);
				 * SubscribeTrans queryTrans = subscribeTransService.selectByDto(trans);
				 * if(queryTrans!=null){ HaveReceiveRefundDto entity = new
				 * HaveReceiveRefundDto(); entity.setDocType(DocTypeEnum.COLLECTION.getNo());
				 * entity.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
				 * entity.setRelationId(queryTrans.getSigId()); subscribeAmount =
				 * haveReceiveRefundService.haveReceiveAmount(entity); }else{
				 */
				reFundDto = new HaveReceiveRefundDto();
				reFundDto.setDocType(DocTypeEnum.COLLECTION.getNo());
				reFundDto.setRelationId(subId);
				reFundDto.setReceivablesType(ReceivablesTypeEnum.SUBSCRIBE.getNo());
				subscribeAmount = queryHaveByDto(reFundDto);
				/* } */

				if (payDepositId == null) {
					map.put("payAepositAmount", payDepositAmount == null ? 0 : payDepositAmount);
				}
				map.put("subscribeAmount", subscribeAmount == null ? 0 : subscribeAmount);
			}

			if (payDepositId == null && subId == null) {
				map.put("payAepositAmount", 0d);
				map.put("subscribeAmount", 0d);
				map.put("total", 0d);
			} else {
				subscribeAmount = subscribeAmount == null ? 0d : subscribeAmount;
				map.put("total", (payDepositAmount + subscribeAmount));
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("signedContractAmount error: ", e);
		}
		return map;
	}

	public double queryHaveByDto(HaveReceiveRefundDto reFundDto) {
		Double value = haveReceiveRefundService.haveReceiveAmount(reFundDto);
		return value == null ? 0d : value;
	}

	/**
	 * 签约更名消息
	 */
	@Override
	public CommonResDTO addNotice_GM(BusinessAbnormaDto businessAbnormaDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			Long customerId = null;
			Long roomId = null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			Long merchantId = null;
			if (null != businessAbnormaDto.getBusinessId()) {
				Long projectId = null;

				if (businessAbnormaDto.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_6.getNo())) {
					Signed signed = signedService.selectById(businessAbnormaDto.getBusinessId());
					if (null != signed) {
						projectId = signed.getProjectId();
						customerId = signed.getCustomerId();
						roomId = signed.getRoomId();
						merchantId = signed.getMerchantId();
					}
					// 签约更名
				} else if (businessAbnormaDto.getBusinessType()
						.equals(BusinessAbnormaEnum.BusinessAbnorma_11.getNo())) {
					// 认购更名
					Subscribe subscribe = subscribeService.selectById(businessAbnormaDto.getBusinessId());
					if (null != subscribe) {
						projectId = subscribe.getProjectId();
						customerId = subscribe.getCustomerId();
						roomId = subscribe.getRoomId();
						merchantId = subscribe.getMerchantId();
					}
				} else {
					// 认筹更名
					PayDeposit payDeposit = payDepositService.selectById(businessAbnormaDto.getBusinessId());
					if (null != payDeposit) {
						projectId = payDeposit.getProjectId();
						customerId = payDeposit.getCustomerId();
						roomId = payDeposit.getRoomId();
						merchantId = payDeposit.getMerchantId();
					}

				}
				if (null != projectId) {
					Project project = projectService.selectById(projectId);
					if (null != project) {
						projectCode = project.getProjectCode();
						projectName = project.getProjectName();
					}
				}
				if (null != roomId) {
					ProjectRoom projectRoom = projectRoomService.selectById(roomId);
					if (null != projectRoom) {
						roomName = projectRoom.getCombinedName();
					} else {
						logger.info("签约更名消息失败,房源不存在! 延期Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("签约更名消息失败,房源不存在!");
						resDto.setResult("0");
						return resDto;
					}
				}

				// 客户名称
				Customer customer = customerService.selectById(customerId);
				if (null != customer) {
					customerName = customer.getCustomerName();
				} else {
					logger.info("签约更名消息失败,客户不存在! 延期Id = " + businessAbnormaDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("签约更名消息失败,客户不存在!");
					resDto.setResult("0");
					return resDto;
				}
			} else {
				logger.info("签约更名消息失败,签约信息不存在! 延期Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("签约更名消息失败,签约信息不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 经纪人
			String userName = "";
			String noticeTypeName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(businessAbnormaDto.getBusinessId());
			if (businessAbnormaDto.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_6.getNo())) {
				noticeTypeName = "签约";
				transactionRelationDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
			} else if (businessAbnormaDto.getBusinessType().equals(BusinessAbnormaEnum.BusinessAbnorma_11.getNo())) {
				transactionRelationDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
				noticeTypeName = "认购";
			}

			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
					.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if (e instanceof UserTask) {
						List<String> userIds = activitiProcessService.getNodeUserId(merchantId, null,
								processInstanceHistoryLog.getProcessDefinitionId(), e.getId());
						for (String userId : userIds) {
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("签约更名消息失败,待发送客户不存在! 签约更名Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("签约更名消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT15' 的消息模板
			// 消息模板: 更名审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "更名审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT15");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName).replace("${agent}",
					userName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "178");
			noticeParamMap.put("noticeTempType", "NT15");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", noticeTypeName + "更名审批申请");
			noticeParamMap.put("merchantId", String.valueOf(businessAbnormaDto.getMerchantId()));
			noticeParamMap.put("projectCode", projectCode);
			noticeParamMap.put("userCode", businessAbnormaDto.getUserCode());
			noticeParamMap.put("accessCode", businessAbnormaDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(businessAbnormaDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			Map<String, String> replaceValuesMap = new HashMap<String, String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId == null ? "" : String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? "" : String.valueOf(customerId));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, noticeTypeName + "更名审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("签约更名消息异常,更名业务Id = " + businessAbnormaDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("签约更名消息异常!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	/**
	 * 签约退房消息
	 */
	@Override
	public CommonResDTO addNotice_TF(BusinessAbnormaDto businessAbnormaDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			Long roomId = null;
			Long customerId = null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			Signed signed = null;
			if (null != businessAbnormaDto.getBusinessId()) {
				signed = signedService.selectById(businessAbnormaDto.getBusinessId());
				if (null != signed) {
					Project project = projectService.selectById(signed.getProjectId());
					if (null != project) {
						projectCode = project.getProjectCode();
						projectName = project.getProjectName();
					}
					ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());
					if (null != projectRoom) {
						roomId = projectRoom.getId();
						roomName = projectRoom.getCombinedName();
					} else {
						logger.info("签约退房消息失败,房源不存在! 退房Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("签约退房消息失败,房源不存在!");
						resDto.setResult("0");
						return resDto;
					}
					// 客户名称
					Customer customer = customerService.selectById(signed.getCustomerId());
					if (null != customer) {
						customerId = customer.getId();
						customerName = customer.getCustomerName();
					} else {
						logger.info("签约退房消息失败,客户不存在! 退房Id = " + businessAbnormaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("签约退房消息失败,客户不存在!");
						resDto.setResult("0");
						return resDto;
					}
				}
			} else {
				logger.info("签约退房消息失败,签约信息不存在! 退房Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("签约退房消息失败,签约信息不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(signed.getId());
			transactionRelationDto.setRelationType(RelationTypeEnum.SIGNED.getNo());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
					.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if (e instanceof UserTask) {
						List<String> userIds = activitiProcessService.getNodeUserId(signed.getMerchantId(), null,
								processInstanceHistoryLog.getProcessDefinitionId(), e.getId());
						for (String userId : userIds) {
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}

			if (userList.size() == 0) {
				logger.info("签约退房消息失败,待发送客户不存在! 退房Id = " + businessAbnormaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("签约退房消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT12' 的消息模板
			// 消息模板: 退房审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "退房审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT12");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName).replace("${agent}",
					userName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "175");
			noticeParamMap.put("noticeTempType", "NT12");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "签约退房审批申请");
			noticeParamMap.put("merchantId", String.valueOf(businessAbnormaDto.getMerchantId()));
			noticeParamMap.put("projectCode", projectCode);
			noticeParamMap.put("userCode", businessAbnormaDto.getUserCode());
			noticeParamMap.put("accessCode", businessAbnormaDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(businessAbnormaDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			Map<String, String> replaceValuesMap = new HashMap<String, String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId == null ? "" : String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? "" : String.valueOf(customerId));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "签约退房审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("签约退房消息异常,退房Id = " + businessAbnormaDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("签约退房消息异常!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	/**
	 * 签约换房提交审批申请 创建并发送提醒消息 subscribeId 签约ID、procInstId 流程实例ID
	 */
	@Override
	public CommonResDTO addSignedNotice(Long signedId, String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 签约
			Signed signed = signedService.selectById(signedId);

			// 客户
			String cusName = "";
			Customer customer = customerService.selectById(signed.getCustomerId());
			if (customer != null) {
				cusName = customer.getCustomerName();
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(signed.getProjectCode());
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
					.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if (e instanceof UserTask) {
						List<String> userIds = activitiProcessService.getNodeUserId(signed.getMerchantId(), null,
								processInstanceHistoryLog.getProcessDefinitionId(), e.getId());
						for (String userId : userIds) {
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}

			// 项目
			/*
			 * String proName = ""; Project project = null; if (signed.getProjectId() !=
			 * null) { project = projectService.selectById(signed.getProjectId()); if
			 * (project != null) { proName = project.getProjectName(); } }
			 */

			// 获取经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(signed.getId());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			// 换房, 获取字典表dictionary_value = 'NT11' 的消息模板
			// 消息模板: 换房：换房审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
			String msgTemp = "换房审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT11");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			// 项目房间
			String roomContent = "";
			ProjectRoom room = projectRoomService.selectById(signed.getRoomId());
			if (room != null) {
				roomContent = room.getCombinedName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomContent).replace("${customer}", cusName).replace("${agent}",
					userName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "174");
			noticeParamMap.put("noticeTempType", "NT11");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "换房审批申请");
			noticeParamMap.put("merchantId", String.valueOf(signed.getMerchantId()));
			noticeParamMap.put("projectCode", signed.getProjectCode());
			noticeParamMap.put("userCode", signed.getUserCode());
			noticeParamMap.put("accessCode", signed.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(signed.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			Map<String, String> replaceValuesMap = new HashMap<String, String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			String action = "换房提交审核提醒";
			resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);

			// 推送消息
			if ("1".equals(resDto.getResult())) {
				// 推送消息待处理......
				// pushMsg(project.getProjectCode(), proName, "NT11", "换房审批申请");
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增换房消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	public void pushMsg(String projectCode, String projectName, String noticeTempType, String actionTitle)
			throws Exception {
		// 1、查询换房审核申请相关推送消息
		// NT11: 换房审核申请
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		// String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00";
		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59";
		MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
		withHouseMrDto.setNoticeTempType(noticeTempType);
		withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
		// loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
		// 推送所有小于 issueTimeAfter 时间的所有消息
		withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
		List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
		if (withHouseMrList != null) {
			for (MessageReceiverDto withHouseMr : withHouseMrList) {
				msgRecList.add(withHouseMr);
			}
		}

		if (msgRecList != null && msgRecList.size() > 0) {
			String noticeIds = "";
			String msgRecIds = "";
			Set<String> noticeIdSet = new HashSet<String>();
			for (MessageReceiverDto msgRecDto : msgRecList) {
				// 开始推送消息
				Map<String, String> pushMap = new HashMap<String, String>();
				pushMap.put("action", "换房提交审核提醒");
				pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
				// pushMap.put("pushType", msgRecDto.getNoticeTempType());
				pushMap.put("pushType", "SHSQ");
				pushMap.put("projectCode", projectCode);
				pushMap.put("projectName", projectName);
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context, msgRecDto.getTitle(),
						pushMap);

				// 消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				// 消息接收人ID'S
				if (StringUtils.isNotEmpty(msgRecIds)) {
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
			}
			// 需更新消息ID'S
			if (!noticeIdSet.isEmpty()) {
				for (String noticeId : noticeIdSet) {
					if (StringUtils.isNotEmpty(noticeIds)) {
						noticeIds += ",";
					}
					noticeIds += noticeId;
				}
			}
			// 更新消息
			NoticeDto noticeDto = new NoticeDto();
			noticeDto.setIsSend(IsSendEnum.SEND.getNo());
			noticeService.updates(noticeDto, noticeIds);
			// 更新接收人
			MessageReceiverDto updateMRDto = new MessageReceiverDto();
			updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
			messageReceiverService.updates(updateMRDto, msgRecIds);
		}
	}

	/**
	 * 创建签约消息
	 * 
	 * @param signedDto
	 * @return
	 */
	@Override
	public CommonResDTO addNotice_QY(SignedDto signedDto, String procInstId, String flag) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			Long roomId = null;
			Long customerId = null;
			String roomName = "";
			String customerName = "";
			String projectCode = "";
			String projectName = "";
			Signed signed = signedService.selectById(signedDto.getId());
			if (null != signed) {
				Project project = projectService.selectById(signed.getProjectId());
				if (null != project) {
					projectCode = project.getProjectCode();
					projectName = project.getProjectName();
				}
				ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());
				if (null != projectRoom) {
					roomId = projectRoom.getId();
					roomName = projectRoom.getCombinedName();
				} else {
					logger.info("签约消息失败,房源不存在! 签约Id = " + signedDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("签约消息失败,房源不存在!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}

				// 客户名称
				Customer customer = customerService.selectById(signed.getCustomerId());
				if (null != customer) {
					customerName = customer.getCustomerName();
					customerId = customer.getId();
				} else {
					logger.info("签约消息失败,客户不存在! 签约Id = " + signedDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("签约消息失败,客户不存在!");
					resDto.setResult(ResultEnum.FAILURE.getNo());
					return resDto;
				}
			}

			// 经纪人
			String userName = "";
			TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
			transactionRelationDto.setBusinessId(signed.getId());
			List<TransactionRelation> transactionRelationList = transactionRelationService
					.selectListByDto(transactionRelationDto);
			if (transactionRelationList.size() > 0) {
				for (int i = 0; i < transactionRelationList.size(); i++) {
					User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
					if (user.getUserName() != null && !"".equals(user.getUserName())) {
						if (transactionRelationList.size() == 1) {
							userName = user.getUserName();
						} else {
							userName += "；经纪人" + (i + 1) + "：" + user.getUserName();
						}
					}
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
					.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
			BpmnModel model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
			if (model != null) {
				Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
				for (FlowElement e : flowElements) {
					if (e instanceof UserTask) {
						List<String> userIds = activitiProcessService.getNodeUserId(signed.getMerchantId(), null,
								processInstanceHistoryLog.getProcessDefinitionId(), e.getId());
						for (String userId : userIds) {
							User user = new User();
							user.setId(Long.valueOf(userId));
							userList.add(user);
						}
					}
				}
			}
			if (userList.size() == 0) {
				logger.info("签约消息失败,待发送客户不存在! 签约Id = " + signedDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("签约消息失败,待发送客户不存在!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}

			// 签约审批申请
			if (flag.equals("1")) {
				// 签约, 获取字典表dictionary_value = 'NT09' 的消息模板
				// 消息模板: 签约审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				String msgTemp = "签约审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
				String sendMsg = "";
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDictionaryValue("NT09");
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if (dic != null) {
					msgTemp = dic.getDictionaryName();
				}
				sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
						.replace("${agent}", userName);
				// 创建提醒消息及消息发送人信息
				Map<String, String> noticeParamMap = new HashMap<String, String>();
				noticeParamMap.put("noticeDicId", "172");
				noticeParamMap.put("noticeTempType", "NT09");
				noticeParamMap.put("sendMsg", sendMsg);
				noticeParamMap.put("title", "签约审批申请");
				noticeParamMap.put("merchantId", String.valueOf(signedDto.getMerchantId()));
				noticeParamMap.put("projectCode", signedDto.getProjectCode());
				noticeParamMap.put("userCode", signedDto.getUserCode());
				noticeParamMap.put("accessCode", signedDto.getAccessCode());
				noticeParamMap.put("createUserId", String.valueOf(signedDto.getCreateUserId()));
				/*
				 * (ym) 提醒内容增加超链接 start
				 */
				Map<String, String> replaceValuesMap = new HashMap<String, String>();
				replaceValuesMap.put(MsgUtil.ROOM_ID, roomId == null ? "" : String.valueOf(roomId));
				replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
				replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? "" : String.valueOf(customerId));
				replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				/*
				 * (ym) 提醒内容增加超链接 end
				 */
				NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

				// 推送消息待处理......
				resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "签约审批申请");
			} else if (flag.equals("2")) {
				// 签约折扣, 获取字典表dictionary_value = 'NT10' 的消息模板
				// 消息模板: 签约折扣审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				String msgTemp = "购房折扣审批申请。房号：${roomName}；客户：${customer}；经纪人：${agent}";
				String sendMsg = "";
				DictionaryDto dicDto = new DictionaryDto();
				dicDto.setDictionaryValue("NT10");
				Dictionary dic = dictionaryService.selectByDto(dicDto);
				if (dic != null) {
					msgTemp = dic.getDictionaryName();
				}
				sendMsg = msgTemp.replace("${roomName}", roomName).replace("${customer}", customerName)
						.replace("${agent}", userName);
				// 创建提醒消息及消息发送人信息
				Map<String, String> noticeParamMap = new HashMap<String, String>();
				noticeParamMap.put("noticeDicId", "173");
				noticeParamMap.put("noticeTempType", "NT10");
				noticeParamMap.put("sendMsg", sendMsg);
				noticeParamMap.put("title", "购房折扣审批申请");
				noticeParamMap.put("merchantId", String.valueOf(signedDto.getMerchantId()));
				noticeParamMap.put("projectCode", signedDto.getProjectCode());
				noticeParamMap.put("userCode", signedDto.getUserCode());
				noticeParamMap.put("accessCode", signedDto.getAccessCode());
				noticeParamMap.put("createUserId", String.valueOf(signedDto.getCreateUserId()));
				/*
				 * (ym) 提醒内容增加超链接 start
				 */
				Map<String, String> replaceValuesMap = new HashMap<String, String>();
				replaceValuesMap.put(MsgUtil.ROOM_ID, roomId == null ? "" : String.valueOf(roomId));
				replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
				replaceValuesMap.put(MsgUtil.CUSTOMER_ID, customerId == null ? "" : String.valueOf(customerId));
				replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customerName);
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
				replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
				noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
				/*
				 * (ym) 提醒内容增加超链接 end
				 */
				NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

				// 推送消息待处理......
				resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "购房折扣审批申请");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("签约消息异常,签约Id = " + signedDto.getId(), e);
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("签约消息异常!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.customer.service.SignedServiceFacade#selectSignedCustomer(java.
	 * lang.Long)
	 */
	@Override
	public Response<SignedDto> selectSignedCustomer(Long id) {
		Response<SignedDto> response = new Response<SignedDto>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			SignedDto entity = signedService.selectSignedCustomer(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<SignedDto> signeRepairData(Signed signed, String params, User user, String paymentMethod) throws Exception {
		Response<SignedDto> response = new Response<SignedDto>();
		// 1、删除原签约记录中的应收款 NeedReceivedFunds
		NeedReceiveRefundDto nrrDto = new NeedReceiveRefundDto();
		nrrDto.setRelationId(signed.getId());
		nrrDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
		nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
		List<NeedReceiveRefund> nrrList = needReceiveRefundService.selectListByDto(nrrDto);
		if (null != nrrList && nrrList.size() > 0) {
			for (NeedReceiveRefund nrr : nrrList) {
				nrrDto = new NeedReceiveRefundDto();
				nrrDto.setId(nrr.getId());
				nrrDto.setUpdateUserId(user.getId());
				nrrDto.setDelFlag(DelFlagEnum.DEL.getNo());
				nrrDto.setRemark(nrr.getRemark() + "|合同信息变更删除原记录");
				needReceiveRefundService.update(nrrDto);
			}
		}
		// 2、删除按揭相关数据
		// 2.1、删除按揭记录
		// 2.2、删除按揭跟进记录
		MortgageRecordDto mrDto = new MortgageRecordDto();
		mrDto.setSignedId(signed.getId());
		List<MortgageRecord> mrList = mortgageRecordService.selectListByDto(mrDto);
		if (null != mrList && mrList.size() > 0) {
			for (MortgageRecord mr : mrList) {
				mrDto = new MortgageRecordDto();
				mrDto.setId(mr.getId());
				mrDto.setUpdateUserId(user.getId());
				mrDto.setDelFlag(DelFlagEnum.DEL.getNo());
				nrrDto.setRemark(mr.getRemark() + "|合同变更删除原记录");
				mortgageRecordService.update(mrDto);
				// 跟进变更记录
				MortgageRecordFollowDto mrfDto = new MortgageRecordFollowDto();
				mrfDto.setMortgageRecordId(mr.getId());
				mortgageRecordFollowService.destroy(mrfDto);
			}
		}
		BigDecimal totalSigneAmount = BigDecimal.ZERO;
		// 3、插入新的待收款记录
		Long firstNeedReceiveId = null;
		int count = 1;
		JSONArray needReceiveArray = JSONArray.parseArray(params);
		if (null != needReceiveArray && needReceiveArray.size() > 0) {
			for (int i = 0; i < needReceiveArray.size(); i++) {
				String needReceiveStr = (String) needReceiveArray.get(i);
				NeedReceiveRefundDto needReceiveRefundDto = JSONObject.parseObject(needReceiveStr,
						NeedReceiveRefundDto.class);
				if (null != needReceiveRefundDto.getTotalReceivablesAmount())
					totalSigneAmount = totalSigneAmount.add(needReceiveRefundDto.getTotalReceivablesAmount());
				needReceiveRefundDto.setRelationId(signed.getId());
				needReceiveRefundDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
				needReceiveRefundDto.setCustomerId(signed.getCustomerId());
				needReceiveRefundDto.setRoomId(signed.getRoomId());
				needReceiveRefundDto.setStatus("1");
				needReceiveRefundDto.setPostponedStatus("0");
				needReceiveRefundDto.setDocType(DocTypeEnum.COLLECTION.getNo());
				needReceiveRefundDto.setRemark("合同信息变更");
				needReceiveRefundDto.setMerchantId(signed.getMerchantId());
				needReceiveRefundDto.setPaymentMethod(paymentMethod);
				needReceiveRefundDto.setUserCode(signed.getUserCode());
				needReceiveRefundDto.setAccessCode(signed.getAccessCode());
				needReceiveRefundDto.setCreateUserId(signed.getCreateUserId());
				needReceiveRefundDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				needReceiveRefundDto.setUpdateUserId(signed.getUpdateUserId());
				needReceiveRefundDto.setUpdateTime(new Date());
				NeedReceiveRefundDto nrrdSaveResponse = needReceiveRefundService.create(needReceiveRefundDto);
				if (null == nrrdSaveResponse) {
					throw new Exception("保存签约应收信息错误");
				}
				if (count == 1) {
					firstNeedReceiveId = nrrdSaveResponse.getId();
				}
				count++;
			}
		}
		// 4、插入新的签约按揭记录
		nrrDto = new NeedReceiveRefundDto();
		nrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
		nrrDto.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
		nrrDto.setRelationId(signed.getId());
		nrrList = needReceiveRefundService.selectListByDto(nrrDto);
		if (null != nrrList && nrrList.size() > 0) {
			for (NeedReceiveRefund nff : nrrList) {
				if (nff.getPaymentMethod().equals(PaymentMethodEnum.LUMP_SUM.getNo())
						|| nff.getPaymentMethod().equals(PaymentMethodEnum.INSTALLMENT_PAYMENT.getNo())) {
					continue;
				}
				String housingFundTyp = nff.getHousingFundType();
				if (housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo())
						|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo())
						|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo())) {
					continue;
				}
				MortgageRecordDto mortgageRecordDto = new MortgageRecordDto();
				mortgageRecordDto.setNeedId(nff.getId());
				mortgageRecordDto.setSignedId(signed.getId());
				mortgageRecordDto.setRoomId(signed.getRoomId());
				mortgageRecordDto.setCustomerId(signed.getCustomerId());
				mortgageRecordDto.setProjectId(signed.getProjectId());
				mortgageRecordDto.setBusinessFlag(nff.getBusinessFlag());
				mortgageRecordDto.setHousingFundType(nff.getHousingFundType());
				ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());
				if (null != projectRoom) {
					mortgageRecordDto.setRoomName(projectRoom.getCombinedName());
				} else {
					mortgageRecordDto.setRoomName("未知");
				}
				Customer customer = customerService.selectById(signed.getCustomerId());
				if (null != customer) {
					mortgageRecordDto.setCustomerName(customer.getCustomerName());
				} else {
					mortgageRecordDto.setCustomerName("未知");
				}

				mortgageRecordDto.setSignedDate(signed.getDidTime());
				mortgageRecordDto.setSignAmount(signed.getSignAmount());
				// 按揭金额
				mortgageRecordDto.setMortgageAmount(nff.getTotalReceivablesAmount());
				mortgageRecordDto.setMortgageReceivedStatus("0");
				mortgageRecordDto.setMortgageCheckStatus("0");
				mortgageRecordDto.setProcessStatus("0");

				mortgageRecordDto.setMerchantId(signed.getMerchantId());
				mortgageRecordDto.setAccessCode(signed.getAccessCode());
				mortgageRecordDto.setCreateUserId(signed.getCreateUserId());
				mortgageRecordDto.setUserCode(signed.getUserCode());
				mortgageRecordDto.setDelFlag("0");
				mortgageRecordDto.setUpdateUserId(signed.getUpdateUserId());
				mortgageRecordDto.setUpdateTime(new Date());
				mortgageRecordDto.setReceivablesFunds(nff.getReceivablesFunds());
				mortgageRecordService.create(mortgageRecordDto);
			}
		}
		// 6、修改签约中的收款方式和合同金额
		SignedDto signedDto = new SignedDto();
		signedDto.setId(signed.getId());
		signedDto.setPaymentMethod(paymentMethod);
		signedDto.setSignAmount(totalSigneAmount);
		signedService.update(signedDto);

		// 删除非转账的已收款
		HaveReceiveRefundDto hrrDto = new HaveReceiveRefundDto();
		hrrDto.setRelationId(signed.getId());
		hrrDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
		hrrDto.setDocType("0");
		List<HaveReceiveRefund> haveList = haveReceiveRefundService.selectListByDto(hrrDto);
		if (null != haveList) {
			for (HaveReceiveRefund hrr : haveList) {
				String businessFlag = hrr.getBusinessFlag();
				if (BusinessFlagEnum.BUSINESSFLAG_12.getNo().equals(businessFlag)
						|| BusinessFlagEnum.BUSINESSFLAG_13.getNo().equals(businessFlag)) {
					// 转过来的金额挂到第一笔应收下面
					if (null != firstNeedReceiveId) {
						HaveReceiveRefundDto deleteDto = new HaveReceiveRefundDto();
						deleteDto.setId(hrr.getId());
						deleteDto.setReceivablesId(firstNeedReceiveId);
						haveReceiveRefundService.update(deleteDto);
					}

				} else {
					HaveReceiveRefundDto deleteDto = new HaveReceiveRefundDto();
					deleteDto.setId(hrr.getId());
					haveReceiveRefundService.destroy(deleteDto);
				}

			}
		}
		response.setSuccess(true);
		response.setResultMessage("签约信息变更成功，请重新收款!");
		return response;
	}

	@Override
	public ResponseList<SignedDto> querySignedDtoExport(SignedDto signedDto) {
		ResponseList<SignedDto> responseList = new ResponseList<SignedDto>();
		try {
			signedDto = setSignedQuery(signedDto);
			signedDto.setIsExport("1");
			Page<SignedDto> page = signedService.getPageDtoModel(signedDto, 0, 0);
			responseList.setEntity(page.getRows());
			responseList.setSuccess(true);
		} catch (Exception e) {
			responseList.setSuccess(false);
			logger.error("querySignedDtoExport error: ", e);
		}
		return responseList;
	}

	@Override
	public Response<Page<SignedDto>> getPageDtoByCustomerId(String customerId, Integer pageSize, Integer pageNum) {
		Response<Page<SignedDto>> resDto = new Response<Page<SignedDto>>();
		try {
			Page<SignedDto> page = service.getPageDtoByCustomerId(customerId, PageUtil.begin(pageNum, pageSize), pageSize);
			page.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(page);
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
		}
		return resDto;
	}

	@Override
	public Page<SignedDto> getSignedInfoPage(SignedDto dto, Integer begin, Integer row) {
		Page<SignedDto> response = new Page<SignedDto>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<SignedDto> page = service.getSignedListPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<SignedDto> getSignedInfoByDto(SignedDto dto) {
		ResponseList<SignedDto> responseList = new ResponseList<SignedDto>();
		try {
			List<SignedDto> signedList = signedService.getSignedListByDto(dto);
			responseList.setEntity(signedList);
			responseList.setSuccess(true);
		} catch (Exception e) {
			responseList.setSuccess(false);
			logger.error("querySignedDtoExport error: ", e);
		}
		return responseList;
	}
}
